<template>
  <div class="wechat-crawl-container">
    <div class="form-side">
      <el-form :model="form" label-width="120px" class="wechat-crawl-form">
        <el-form-item label="文章链接">
          <el-input 
            v-model="form.article_url" 
            placeholder="请输入公众号文章链接" 
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="批量链接">
          <el-input 
            v-model="form.batch_urls" 
            placeholder="请输入多个文章链接，每行一个" 
            type="textarea"
            :rows="6"
          />
          <div class="form-tip">支持批量爬取，每行输入一个链接</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="crawlSingle" :loading="singleLoading">
            爬取单篇文章
          </el-button>
          <el-button 
            type="success" 
            @click="crawlBatch" 
            :loading="batchLoading"
            style="margin-left: 8px;"
          >
            批量爬取
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-side">
      <div style="margin-bottom: 16px; display: flex; align-items: center; justify-content: space-between;">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文章标题"
          style="width: 300px;"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="refreshList">刷新列表</el-button>
      </div>
      <el-table :data="tableData" :loading="tableLoading" style="width: 100%">
        <el-table-column width="300" prop="title" label="文章标题" show-overflow-tooltip />
        <el-table-column width="200" prop="content" label="内容预览" show-overflow-tooltip />
        <el-table-column width="120" prop="source" label="来源" />
        <el-table-column width="180" prop="created_time" label="创建时间" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="viewDetail(row)"
            >查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 16px; text-align: right"
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 文章详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="文章详情"
      width="60%"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentArticle">
        <h3>{{ currentArticle.title }}</h3>
        <p><strong>来源：</strong>{{ currentArticle.source }}</p>
        <p><strong>创建时间：</strong>{{ currentArticle.created_time }}</p>
        <p><strong>链接：</strong><a :href="currentArticle.url" target="_blank">{{ currentArticle.url }}</a></p>
        <div class="article-content">
          <h4>文章内容：</h4>
          <div class="content-text">{{ currentArticle.content }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

const form = ref({
  article_url: '',
  batch_urls: ''
})

const singleLoading = ref(false)
const batchLoading = ref(false)
const tableLoading = ref(false)
const tableData = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const detailVisible = ref(false)
const currentArticle = ref<any>(null)

// 爬取单篇文章
const crawlSingle = async () => {
  if (!form.value.article_url.trim()) {
    ElMessage.warning('请输入文章链接')
    return
  }

  singleLoading.value = true
  try {
    const response = await axios.post('/api/crawl_wechat_article/', {
      article_url: form.value.article_url.trim()
    })
    
    if (response.data.success) {
      ElMessage.success(`文章爬取成功：${response.data.title}`)
      form.value.article_url = ''
      fetchTableData()
    } else {
      ElMessage.error(`爬取失败：${response.data.error}`)
    }
  } catch (error: any) {
    ElMessage.error(`请求失败：${error.response?.data?.error || error.message}`)
  } finally {
    singleLoading.value = false
  }
}

// 批量爬取文章
const crawlBatch = async () => {
  if (!form.value.batch_urls.trim()) {
    ElMessage.warning('请输入文章链接')
    return
  }

  const urls = form.value.batch_urls.trim().split('\n').filter(url => url.trim())
  if (urls.length === 0) {
    ElMessage.warning('请输入有效的文章链接')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量爬取 ${urls.length} 篇文章吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  batchLoading.value = true
  try {
    const response = await axios.post('/api/batch_crawl_wechat_articles/', {
      article_urls: urls
    })
    
    if (response.data.success) {
      ElMessage.success(`批量爬取完成，成功 ${response.data.success_count}/${response.data.total} 篇`)
      form.value.batch_urls = ''
      fetchTableData()
    } else {
      ElMessage.error(`批量爬取失败：${response.data.error}`)
    }
  } catch (error: any) {
    ElMessage.error(`请求失败：${error.response?.data?.error || error.message}`)
  } finally {
    batchLoading.value = false
  }
}

// 获取文章列表
const fetchTableData = async () => {
  tableLoading.value = true
  try {
    const response = await axios.get('/api/wechat_article_list/', {
      params: {
        page: page.value,
        page_size: pageSize.value,
        search: searchKeyword.value
      }
    })
    
    tableData.value = response.data.data || []
    total.value = response.data.total
  } catch (error: any) {
    ElMessage.error(`获取列表失败：${error.response?.data?.error || error.message}`)
  } finally {
    tableLoading.value = false
  }
}

// 查看文章详情
const viewDetail = async (row: any) => {
  try {
    const response = await axios.get(`/api/wechat_article_detail/${row.id}/`)
    currentArticle.value = response.data
    detailVisible.value = true
  } catch (error: any) {
    ElMessage.error(`获取详情失败：${error.response?.data?.error || error.message}`)
  }
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailVisible.value = false
  currentArticle.value = null
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchTableData()
}

// 刷新列表
const refreshList = () => {
  fetchTableData()
}

// 分页
const handlePageChange = (newPage: number) => {
  page.value = newPage
  fetchTableData()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>
.wechat-crawl-container {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  width: 100%;
  gap: 0;
  min-height: 600px;
}

.form-side {
  width: 350px;
  min-width: 350px;
  max-width: 350px;
  border-right: 1px solid #e0e0e0;
  padding-right: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.table-side {
  flex: 1;
  min-width: 0;
  padding-left: 20px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.wechat-crawl-form {
  background: #fff;
  padding: 0;
  border-radius: 8px;
  box-shadow: none;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.article-content {
  margin-top: 20px;
}

.content-text {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  max-height: 400px;
  overflow-y: auto;
  white-space: pre-wrap;
  line-height: 1.6;
}

@media (max-width: 1200px) {
  .wechat-crawl-container {
    flex-direction: column;
  }
  
  .form-side {
    width: 100%;
    min-width: 100%;
    max-width: 100%;
    border-right: none;
    border-bottom: 1px solid #e0e0e0;
    padding-right: 0;
    padding-bottom: 20px;
    margin-bottom: 20px;
  }
  
  .table-side {
    padding-left: 0;
  }
}
</style> 